<template>
  <div class="user">
    <el-card class="box-card">
      <!-- 查询区 -->
      <el-form ref="queryFormRef" :model="queryInfo" size="small" :inline="true">
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="queryInfo.username"
            clearable
            @keyup.enter.native="handleQuery"
            placeholder="请输入用户名搜索"
          ></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input
            v-model="queryInfo.realName"
            @keyup.enter.native="handleQuery"
            clearable
            placeholder="请输入真实姓名搜索"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="queryInfo.role" placeholder="请选择">
            <el-option label="全部" value></el-option>
            <el-option label="管理员" value="ROLE_admin"></el-option>
            <el-option label="HR" value="ROLE_user"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryInfo.status" placeholder="请选择">
            <el-option label="全部" value></el-option>
            <el-option label="正常" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" type="primary" @click="handleQuery">查询</el-button>
          <el-button size="mini" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 操作区 -->
      <div class="operation">
        <el-button size="mini" type="primary" icon="el-icon-plus" @click="dialogVisible = true">添加</el-button>
        <el-button
          size="mini"
          type="danger"
          icon="el-icon-delete"
          :disabled="selectUserLength === 0"
          @click="handleDelListUser"
        >批量删除</el-button>
      </div>
      <!-- 表格 -->
      <el-table
        ref="multipleTable"
        :data="userListData"
        tooltip-effect="dark"
        style="width: 100%;"
        v-loading="loading"
        :header-cell-style="{ background: '#f8f8f9', color: '#515a6e' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="#" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="realName" label="真实姓名" />
        <el-table-column prop="phone" label="手机号码" />
        <el-table-column label="角色">
          <template slot-scope="scope">
            <el-select
              ref="roleSelectRef"
              v-if="scope.row.isEditRoleStatus"
              :value="scope.row.role"
              @change="handleRoleChange(scope.row, $event)"
              @blur="handleRoleBlur(scope.row)"
            >
              <el-option label="管理员" value="ROLE_admin"></el-option>
              <el-option label="HR" value="ROLE_user"></el-option>
            </el-select>
            <div class="operation-role-edit" v-else>
              <span>{{ scope.row.role === 'ROLE_admin' ? '管理员' : 'HR' }}</span>
              <el-button
                type="text"
                v-if="scope.row.id !== 1"
                icon="el-icon-edit"
                @click="handleEditRole(scope.row)"
              ></el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              :disabled="scope.row.id === 1"
              @change="handleChangeUserStatus(scope.row, $event)"
              :value="scope.row.status"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="handleDelOneUser(scope.row)" icon="el-icon-delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="getUserListData"
        @current-change="getUserListData"
        :current-page.sync="queryInfo.pageNum"
        :page-sizes="[10, 20, 30]"
        :page-size.sync="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <add-form @addUserSuccess="addUserSuccess" :dialogVisible="dialogVisible" />
    </el-dialog>
  </div>
</template>

<script>
import {
  listUserApi,
  delOneUserApi,
  delListUserApi,
  changeUserStatusApi,
  changeUserRoleApi,
} from "@/api/user";
import AddForm from "./AddForm";
export default {
  name: "User",
  data() {
    return {
      queryInfo: {
        // 当前页
        pageNum: 1,
        // 页大小
        pageSize: 10,
        // 用户名
        username: "",
        // 真实姓名
        realName: "",
        // 角色
        role: "",
        // 状态
        status: "",
      },
      total: 0,
      userListData: [],
      loading: false,
      multipleSelection: [],
      dialogVisible: false,
    };
  },
  created() {
    this.getUserListData();
  },
  computed: {
    selectUserLength() {
      return this.multipleSelection.length;
    },
  },
  methods: {
    // 获取数据
    async getUserListData() {
      try {
        this.loading = true;
        const { data, code } = await listUserApi(this.queryInfo);
        if (code !== 200) return;
        data.users.forEach((item) => {
          item.isEditRoleStatus = false;
        });
        this.userListData = data.users;
        this.total = data.total;
      } finally {
        this.loading = false;
      }
    },

    // 表格多选
    handleSelectionChange(val) {
      this.multipleSelection = val.filter((item) => item.id !== 1);
    },
    // 关键字查询
    handleQuery() {
      this.queryInfo.pageNum = 1;
      this.getUserListData();
    },
    // 重置表单
    handleReset() {
      this.$refs.queryFormRef.resetFields();
      this.getUserListData();
    },

    //删除单个用户
    handleDelOneUser(user) {
      this.confirm(`删除用户${user.username}`, async () => {
        const { code } = await delOneUserApi(user.id);
        if (code !== 200) return Promise.reject();
        this.getUserListData();
      });
    },

    // 批量删除用户
    handleDelListUser() {
      const delUsername = this.multipleSelection
        .map((item) => item.username)
        .join(",");
      this.confirm(`批量删除用户${delUsername}`, async () => {
        const { code } = await delListUserApi(
          this.multipleSelection.map((item) => item.id)
        );
        if (code !== 200) return Promise.reject();
        this.getUserListData();
      });
    },
    //处理切换用户状态
    handleChangeUserStatus(user, value) {
      this.confirm(
        `将改变用户${user.username}的状态为${value ? "正常" : "禁用"}`,
        async () => {
          const { code } = await changeUserStatusApi(user.id);
          if (code !== 200) return Promise.reject();
          user.status = value;
        },
        "更改用户状态"
      );
    },
    // 切换角色编辑状态
    handleEditRole(user) {
      user.isEditRoleStatus = true;
      this.$nextTick(() => {
        this.$refs.roleSelectRef.focus();
      });
    },
    //角色编辑框失焦时
    handleRoleBlur(user) {
      user.isEditRoleStatus = false;
    },

    // 改变用户角色
    handleRoleChange(user, value) {
      console.log(value);
      this.confirm(
        `切换用户的角色为${value === "ROLE_admin" ? "管理员" : "HR"}`,
        async () => {
          const { code } = await changeUserRoleApi(user.id, value);
          if (code !== 200) return Promise.reject();
          user.role = value;
        },
        "更改用户角色"
      );
    },
    // 封装应答框
    confirm(title, cb, operation = "删除") {
      this.$confirm(`此操作将${title}, 是否继续?, 提示`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            await cb();
            this.$message.success(`${operation}成功!`);
          } catch {
            this.$message.error(`${operation}失败!`);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: `已取消${operation}`,
          });
        });
    },
    // 添加用户成功关闭对话框
    addUserSuccess() {
      this.dialogVisible = false;
      this.getUserListData();
    },
  },
  components: {
    AddForm,
  },
};
</script>

<style scoped lang="scss">
.operation {
  .el-button {
    margin-bottom: 18px;
  }
}
.el-pagination {
  margin: 18px 0px;
  float: right;
}
.operation-role-edit {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
